package cn.pupil.design.event;

import cn.pupil.design.LotteryResult;
import cn.pupil.design.event.listener.EventListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 监听事件管理类，进行事件处理
 * @Author: pupil
 * @Date: 2024/07/30 下午 6:56
 */
public class EventManager {

    private Map<Enum<EventType>, List<EventListener>> listeners = new HashMap<>();

    public EventManager(Enum<EventType>... operations) {
        for (Enum<EventType> operation : operations) {
            this.listeners.put(operation, new ArrayList<>());
        }
    }

    public enum EventType {
        MQ,
        Message
    }

    /**
     * 订阅
     *
     * @param eventType 事件类型
     * @param listener  监听
     */
    public void subscribe(Enum<EventType> eventType, EventListener listener) {
        List<EventListener> users = this.listeners.get(eventType);
        users.add(listener);
    }

    /**
     * 取消订阅
     *
     * @param eventType 事件类型
     * @param listener  监听
     */
    public void unsubscribe(Enum<EventType> eventType, EventListener listener) {
        List<EventListener> users = this.listeners.get(eventType);
        users.remove(listener);
    }

    /**
     * 通知
     *
     * @param eventType 事件类型
     * @param result    结果
     */
    public void notify(Enum<EventType> eventType, LotteryResult result) {
        List<EventListener> users = listeners.get(eventType);
        for (EventListener listener : users) {
            listener.doEvent(result);
        }
    }

    /**
     * 所有通知
     *
     * @param result
     */
    public void notifyAll(LotteryResult result) {
        listeners.forEach((k, v) -> {
            List<EventListener> users = listeners.get(k);
            if (users.size() > 0) {
                for (EventListener user : users) {
                    user.doEvent(result);
                }
            }
        });
    }
}
